import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义任务管理store (组合式API)
export const useTaskStore = defineStore('tasks', () => {
  // state
  const tasks = ref([
    { id: 1, title: '学习Vue基础', completed: true },
    { id: 2, title: '学习Pinia状态管理', completed: false },
    { id: 3, title: '构建一个项目', completed: false }
  ])
  
  const nextId = ref(4)
  
  const user = ref({
    name: '张三',
    role: '开发者'
  })
  
  const settings = ref({
    darkMode: false,
    notifications: true,
    language: 'zh-CN'
  })
  
  // getters
  const unfinishedTasks = computed(() => {
    return tasks.value.filter(task => !task.completed)
  })
  
  const completedTasks = computed(() => {
    return tasks.value.filter(task => task.completed)
  })
  
  const completionRate = computed(() => {
    if (tasks.value.length === 0) return 0
    return tasks.value.filter(task => task.completed).length / tasks.value.length
  })
  
  // actions
  function addTask(title) {
    tasks.value.push({
      id: nextId.value++,
      title,
      completed: false
    })
  }
  
  function removeTask(taskId) {
    const index = tasks.value.findIndex(task => task.id === taskId)
    if (index !== -1) {
      tasks.value.splice(index, 1)
    }
  }
  
  function toggleTask(taskId) {
    const task = tasks.value.find(task => task.id === taskId)
    if (task) {
      task.completed = !task.completed
    }
  }
  
  function updateUser(userData) {
    user.value = { ...user.value, ...userData }
  }
  
  function updateSettings(newSettings) {
    settings.value = { ...settings.value, ...newSettings }
  }
  
  function resetTasksStatus(completed = false) {
    tasks.value.forEach(task => {
      task.completed = completed
    })
  }
  
  return {
    // state
    tasks,
    nextId,
    user,
    settings,
    // getters
    unfinishedTasks,
    completedTasks,
    completionRate,
    // actions
    addTask,
    removeTask,
    toggleTask,
    updateUser,
    updateSettings,
    resetTasksStatus
  }
})
